package com.whut.report;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONArray;
import com.whut.common.ReportCommonFunc;
import com.whut.model.ContractTaskProject;
import com.whut.model.Profiles;
import com.whut.model.UrlProperties;
import com.whut.parMapper.ParProblemCollectDetailMapper;
import com.whut.parMapper.ParProblemDescriptionMapper;
import com.whut.parMapper.ParSystemMapper;
import com.whut.parMapper.utils.MapperUtils;
import com.whut.service.impl.ReportServiceImpl;
import com.whut.utils.MDoc;
import com.whut.v_dataMap.EquipAssessDataMap.*;
import com.whut.v_model.ProblemCollectDetail;
import com.whut.v_vo.EquipRiskNumVO;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class HouseEquipAssessReport {
    private ParSystemMapper parSystemMapper;
    private ParProblemDescriptionMapper parProblemDescriptionMapper;
    private ParProblemCollectDetailMapper parProblemCollectDetailMapper;
    private ReportServiceImpl reportServiceImpl;
    @Resource
    private UrlProperties urlProperties;
    @Resource
    private Profiles profiles;
    private MapperUtils mapperUtils;

    private int checkId;
    private int projectId;
    private boolean isNew;
    public static final int WIDTH = 718;
    public static final int HEIGHT = 468;
    public HouseEquipAssessReport(ParSystemMapper parSystemMapper,
                                  ParProblemDescriptionMapper parProblemDescriptionMapper,
                                  ParProblemCollectDetailMapper parProblemCollectDetailMapper,
                                  ReportServiceImpl reportServiceImpl,
                                  MapperUtils mapperUtils,
                                  UrlProperties urlProperties,
                                  Profiles profiles){
        this.parSystemMapper = parSystemMapper;
        this.parProblemDescriptionMapper = parProblemDescriptionMapper;
        this.parProblemCollectDetailMapper = parProblemCollectDetailMapper;
        this.reportServiceImpl = reportServiceImpl;
        this.mapperUtils=mapperUtils;
        this.urlProperties=urlProperties;
        this.urlProperties=urlProperties;
        this.profiles=profiles;
    }
    public String houseEquipAssessReport(int checkId, int projectId, int reportType) {

        //dataMap存储报告中的所有数据
        HouseEquipAssessDataMap dataMap = new HouseEquipAssessDataMap();

        //报告日期和报告命名需要的时间信息
        DateTimeFormatter dateFormatterYear = DateTimeFormatter.ofPattern("yyyy");
        String year = dateFormatterYear.format(LocalDate.now());
        dataMap.setYear(year);
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String reportDate = dateFormatter.format(LocalDate.now());
        dataMap.setReportDate(reportDate);

        //第一部分 ----- 一、工程概况
        ContractTaskProject projectInfo = mapperUtils.getContractTaskProjectMapper().getProjectInfoByProjectId(projectId);
        dataMap.setProjectName(projectInfo.getProjectName());
        dataMap.setJsUnit(projectInfo.getJsUnit());
        dataMap.setJlUnit(projectInfo.getJlUnit());
        dataMap.setSgUnit(projectInfo.getSgUnit());

        //第一部分 ----- 二、评估结果 ----- （一）设备专项评估结果

        List<sbzxPart2Seg1Map> sbzxPart2Seg1MapList = mapperUtils.getMachineinfoMapper().getEquipNumberInfo(projectId);
        //记录各个专业的问题分布
        List<wtfbPart2Seg2Map> wtfbPart2Seg2MapList = new LinkedList<>();
        int wtfbNumber = 1;
        for (sbzxPart2Seg1Map sbzxPart2Seg1MapItem : sbzxPart2Seg1MapList) {

            //问题分布的相关信息
            wtfbPart2Seg2Map wtfbPart2Seg2MapItem = new wtfbPart2Seg2Map();
            wtfbPart2Seg2MapItem.setWtfbNumber(wtfbNumber++);
            wtfbPart2Seg2MapItem.setWtfbType(sbzxPart2Seg1MapItem.getSbzxName());
            int wtfbNum = 0;

            List<sbzxPart2Seg1InnerMap> sbzxPart2Seg1InnerMapList = sbzxPart2Seg1MapItem.getSbzxPart2Seg1InnerList();
            //计算每台设备得分
            for (sbzxPart2Seg1InnerMap sbzxPart2Seg1InnerMapItem : sbzxPart2Seg1InnerMapList) {

                //算有问题项的得分
                List<Map<String, Double>> scoreList = new LinkedList<>();
                List<ProblemCollectDetail> problemList = parProblemCollectDetailMapper.getEquipProblems(sbzxPart2Seg1InnerMapItem.getSbzxEquipName(), checkId, sbzxPart2Seg1MapItem.getMachineType());
                for (ProblemCollectDetail problemCollectDetail : problemList) {
                    Map<String, Double> problemScoreMap = new HashMap<>();
                    problemScoreMap.put("deductScore", Double.parseDouble(problemCollectDetail.getPoint6()) - Double.parseDouble(problemCollectDetail.getReducePoint()));
                    problemScoreMap.put("totalScore", Double.parseDouble(problemCollectDetail.getPoint6()));
                    scoreList.add(problemScoreMap);
                }
                //记录问题数量
                wtfbNum = wtfbNum + problemList.size();

                //计算无问题项的得分
                List<Integer> noProblemNum = mapperUtils.getNoproblemitemMapper().getNoProblemSixId(sbzxPart2Seg1InnerMapItem.getSbzxEquipName(), checkId, sbzxPart2Seg1MapItem.getMachineType());
                for (Integer noProblemNumItem : noProblemNum) {
                    double noProblemNumScore = Double.parseDouble(parSystemMapper.getPoint4ByPoint4Id(noProblemNumItem));
                    Map<String, Double> noProblemScoreMap = new HashMap<>();
                    noProblemScoreMap.put("deductScore", noProblemNumScore);
                    noProblemScoreMap.put("totalScore", noProblemNumScore);
                    scoreList.add(noProblemScoreMap);
                }

                //计算每台设备的最终得分
                Map<String, Double> scoreResultMap = scoreList.stream()
                        .reduce(new HashMap<String, Double>(), (res, item) -> {
                            res.put("deductScore", res.getOrDefault("deductScore", (double) 0) + item.get("deductScore"));
                            res.put("totalScore", res.getOrDefault("totalScore", (double) 0) + item.get("totalScore"));
                            return res;
                        });
                double singleEquipScore = scoreResultMap.get("deductScore") / scoreResultMap.get("totalScore") * 100;
                sbzxPart2Seg1InnerMapItem.setSbzxEquipScore((double) Math.round(singleEquipScore * 100) / 100);
            }
            //计算平均分，得分项得分
            double equipScore = sbzxPart2Seg1InnerMapList.stream()
                    .mapToDouble(sbzxPart2Seg1InnerMap::getSbzxEquipScore)
                    .average()
                    .getAsDouble();
            sbzxPart2Seg1MapItem.setSbzxScore((double) Math.round(equipScore * 100) / 100);

            wtfbPart2Seg2MapItem.setWtfbNum(wtfbNum);
            wtfbPart2Seg2MapList.add(wtfbPart2Seg2MapItem);
        }

        //房建报告不同于市政报告的地方
        //计算权重和分数要根据具体情况进行计算（这写法整复杂了,不如直接写sql
        Map<Boolean, List<sbzxPart2Seg1Map>> sbzxPart2Seg1MapList02 = sbzxPart2Seg1MapList.stream()
                .collect(Collectors.groupingBy(a -> StringUtils.equals(a.getSbzxName(), "施工升降机") || StringUtils.equals(a.getSbzxName(), "物料提升机")));

        List<sbzxPart2Seg1Map> sbzxPart2Seg1MapListsjj = sbzxPart2Seg1MapList02.get(true);
        List<sbzxPart2Seg1Map> sbzxPart2Seg1MapListqzj = sbzxPart2Seg1MapList02.get(false);
        double sbzxScore01 = 0;
        if (sbzxPart2Seg1MapListqzj != null && sbzxPart2Seg1MapListqzj.size() == 1) {
            sbzxPart2Seg1Map sbzxPart2Seg1MapItem = sbzxPart2Seg1MapListqzj.get(0);
            sbzxPart2Seg1MapItem.setSbzxWeight("100%");
            sbzxScore01 = sbzxScore01 + sbzxPart2Seg1MapItem.getSbzxScore();
        } else if (sbzxPart2Seg1MapListqzj != null && sbzxPart2Seg1MapList02.get(false).size() == 2) {
            for (sbzxPart2Seg1Map sbzxPart2Seg1MapItem : sbzxPart2Seg1MapListqzj) {
                if (StringUtils.equals(sbzxPart2Seg1MapItem.getSbzxName(), "塔式起重机")) {
                    sbzxPart2Seg1MapItem.setSbzxWeight("60%");
                    sbzxScore01 = sbzxScore01 + sbzxPart2Seg1MapItem.getSbzxScore() * 0.6;
                } else {
                    sbzxPart2Seg1MapItem.setSbzxWeight("40%");
                    sbzxScore01 = sbzxScore01 + sbzxPart2Seg1MapItem.getSbzxScore() * 0.4;
                }
            }
        }
        double sbzxScore02 = 0;
        if (sbzxPart2Seg1MapListsjj != null && sbzxPart2Seg1MapListsjj.size() == 1) {
            sbzxPart2Seg1Map sbzxPart2Seg1MapItem = sbzxPart2Seg1MapListsjj.get(0);
            sbzxPart2Seg1MapItem.setSbzxWeight("100%");
            sbzxScore02 = sbzxScore02 + sbzxPart2Seg1MapItem.getSbzxScore();
        } else if (sbzxPart2Seg1MapListsjj != null && sbzxPart2Seg1MapListsjj.size() == 2) {
            for (sbzxPart2Seg1Map sbzxPart2Seg1MapItem : sbzxPart2Seg1MapListsjj) {
                if (StringUtils.equals(sbzxPart2Seg1MapItem.getSbzxName(), "施工升降机")) {
                    sbzxPart2Seg1MapItem.setSbzxWeight("60%");
                    sbzxScore02 = sbzxScore02 + sbzxPart2Seg1MapItem.getSbzxScore() * 0.6;
                } else if (StringUtils.equals(sbzxPart2Seg1MapItem.getSbzxName(), "物料提升机")) {
                    sbzxPart2Seg1MapItem.setSbzxWeight("40%");
                    sbzxScore02 = sbzxScore02 + sbzxPart2Seg1MapItem.getSbzxScore() * 0.4;
                }
            }
        }

        List<sbzxPart2Seg1PreMap> sbzxPart2Seg1PreList = new LinkedList<>();
        double sbzxScore = 0;
        if (sbzxPart2Seg1MapListsjj != null && sbzxPart2Seg1MapListsjj.size() != 0 && sbzxPart2Seg1MapListqzj != null && sbzxPart2Seg1MapListqzj.size() != 0) {
            sbzxScore = sbzxScore01 * 0.5 + sbzxScore02 * 0.5;
            sbzxPart2Seg1PreMap sbzxPart2Seg1PreMapItem01 = new sbzxPart2Seg1PreMap("塔式起重机与起重吊装", "50%", sbzxPart2Seg1MapListqzj);
            sbzxPart2Seg1PreMap sbzxPart2Seg1PreMapItem02 = new sbzxPart2Seg1PreMap("施工升降机与物料提升机", "50%", sbzxPart2Seg1MapListsjj);
            sbzxPart2Seg1PreList.add(sbzxPart2Seg1PreMapItem01);
            sbzxPart2Seg1PreList.add(sbzxPart2Seg1PreMapItem02);
        } else if (sbzxPart2Seg1MapListsjj != null && sbzxPart2Seg1MapListsjj.size() != 0 && (sbzxPart2Seg1MapListqzj == null || sbzxPart2Seg1MapListqzj.size() == 0)) {
            sbzxScore = sbzxScore02;
            sbzxPart2Seg1PreMap sbzxPart2Seg1PreMapItem02 = new sbzxPart2Seg1PreMap("施工升降机与物料提升机", "100%", sbzxPart2Seg1MapListsjj);
            sbzxPart2Seg1PreList.add(sbzxPart2Seg1PreMapItem02);
        } else if ((sbzxPart2Seg1MapListsjj == null || sbzxPart2Seg1MapListsjj.size() == 0) && sbzxPart2Seg1MapListqzj != null && sbzxPart2Seg1MapListqzj.size() != 0) {
            sbzxScore = sbzxScore01;
            sbzxPart2Seg1PreMap sbzxPart2Seg1PreMapItem01 = new sbzxPart2Seg1PreMap("塔式起重机与起重吊装", "100%", sbzxPart2Seg1MapListqzj);
            sbzxPart2Seg1PreList.add(sbzxPart2Seg1PreMapItem01);
        }

        dataMap.setSbzxScore((double) (Math.round(sbzxScore * 100) * 1.0 / 100));
        dataMap.setSbzxPart2Seg1PreList(sbzxPart2Seg1PreList);

        //第一部分 ----- 二、评估结果 ----- （二）各个专业的问题分布
        //在计算设备专项评估结果的过程中进行了计数
        //过滤问题数量为0的数据（用filter和forEach也可以）
        for (int i = 0; i < wtfbPart2Seg2MapList.size(); i++) {
            if (wtfbPart2Seg2MapList.get(i).getWtfbNum() == 0) {
                wtfbPart2Seg2MapList.remove(i);
            }
        }
        int wtfbNumSum = wtfbPart2Seg2MapList.stream()
                .mapToInt(wtfbPart2Seg2Map::getWtfbNum)
                .sum();
        for (wtfbPart2Seg2Map wtfbPart2Seg2MapItem : wtfbPart2Seg2MapList) {
            String wtfbPercent = reportServiceImpl.calculatePercent(wtfbPart2Seg2MapItem.getWtfbNum(), wtfbNumSum);
            wtfbPart2Seg2MapItem.setWtfbPercent(wtfbPercent);
        }
        dataMap.setWtfbNumSum(wtfbNumSum);
        dataMap.setWtfbPart2Seg2List(wtfbPart2Seg2MapList);

        //第一部分 ----- 二、评估结果 ----- （三）设备信息及检查情况
        List<jcqkPart2Seg3Map> jcqkPart2Seg3MapList = mapperUtils.getMachineinfoMapper().getEquipUnitInfo(projectId);
        //计算设备数量
        for (jcqkPart2Seg3Map jcqkPart2Seg3MapItem : jcqkPart2Seg3MapList) {
            int jcqkEquipNum = 0;
            for (jcqkPart2Seg3Inner1Map jcqkPart2Seg3Inner1MapItem : jcqkPart2Seg3MapItem.getJcqkPart2Seg3Inner1List()) {
                jcqkEquipNum = jcqkEquipNum + jcqkPart2Seg3Inner1MapItem.getJcqkPart2Seg3Inner2List().size();
            }
            jcqkPart2Seg3MapItem.setJcqkEquipNum(jcqkEquipNum);
        }
        //计算3、4级隐患数量
        List<jcqkPart2Seg3Inner2Map> jcqkPart2Seg3Inner2MapList = mapperUtils.getMachineinfoMapper().getEquipRiskNum(checkId, projectId);
        for (jcqkPart2Seg3Map jcqkPart2Seg3MapItem : jcqkPart2Seg3MapList) {
            for (jcqkPart2Seg3Inner1Map jcqkPart2Seg3Inner1MapItem : jcqkPart2Seg3MapItem.getJcqkPart2Seg3Inner1List()) {
                for (jcqkPart2Seg3Inner2Map jcqkPart2Seg3Inner2MapItem : jcqkPart2Seg3Inner1MapItem.getJcqkPart2Seg3Inner2List()) {

                    for (jcqkPart2Seg3Inner2Map jcqkPart2Seg3Inner2MapRiskItem : jcqkPart2Seg3Inner2MapList) {
                        if (StringUtils.equals(jcqkPart2Seg3Inner2MapRiskItem.getJcqkEquipCode(), jcqkPart2Seg3Inner2MapItem.getJcqkEquipCode())) {
                            jcqkPart2Seg3Inner2MapItem.setJcqkLevel3Num(jcqkPart2Seg3Inner2MapRiskItem.getJcqkLevel3Num());
                            jcqkPart2Seg3Inner2MapItem.setJcqkLevel4Num(jcqkPart2Seg3Inner2MapRiskItem.getJcqkLevel4Num());
                        }
                    }
                }
            }
        }
        //合计隐患数量
        for (jcqkPart2Seg3Map jcqkPart2Seg3MapItem : jcqkPart2Seg3MapList) {
            for (jcqkPart2Seg3Inner1Map jcqkPart2Seg3Inner1MapItem : jcqkPart2Seg3MapItem.getJcqkPart2Seg3Inner1List()) {
                int jcqkLevel3NumSum = jcqkPart2Seg3Inner1MapItem.getJcqkPart2Seg3Inner2List()
                        .stream()
                        .mapToInt(jcqkPart2Seg3Inner2Map::getJcqkLevel3Num)
                        .sum();
                int jcqkLevel4NumSum = jcqkPart2Seg3Inner1MapItem.getJcqkPart2Seg3Inner2List()
                        .stream()
                        .mapToInt(jcqkPart2Seg3Inner2Map::getJcqkLevel4Num)
                        .sum();
                jcqkPart2Seg3Inner1MapItem.setJcqkLevel3NumSum(jcqkLevel3NumSum);
                jcqkPart2Seg3Inner1MapItem.setJcqkLevel4NumSum(jcqkLevel4NumSum);
            }
        }
        dataMap.setJcqkPart2Seg3List(jcqkPart2Seg3MapList);

        //第一部分 ----- 二、评估结果 ----- （四）隐患分布表
        EquipRiskNumVO equipRiskNumSum = mapperUtils.getMachineinfoMapper().getEquipRiskNumSum(checkId, projectId);
        BeanUtil.copyProperties(equipRiskNumSum, dataMap, CopyOptions.create().setIgnoreNullValue(true));
        //BeanUtils.copyProperties(equipRiskNumSum,dataMap);
        //计算百分比和隐患合计数量
        if (equipRiskNumSum != null) {
            int yhfbNumSum = equipRiskNumSum.getYhfb0Num() + equipRiskNumSum.getYhfb1Num() + equipRiskNumSum.getYhfb2Num() + equipRiskNumSum.getYhfb3Num() + equipRiskNumSum.getYhfb4Num();
            dataMap.setYhfbNumSum(yhfbNumSum);
            dataMap.setYhfb0Percent(reportServiceImpl.calculatePercent(equipRiskNumSum.getYhfb0Num(), yhfbNumSum));
            dataMap.setYhfb1Percent(reportServiceImpl.calculatePercent(equipRiskNumSum.getYhfb1Num(), yhfbNumSum));
            dataMap.setYhfb2Percent(reportServiceImpl.calculatePercent(equipRiskNumSum.getYhfb2Num(), yhfbNumSum));
            dataMap.setYhfb3Percent(reportServiceImpl.calculatePercent(equipRiskNumSum.getYhfb3Num(), yhfbNumSum));
            dataMap.setYhfb4Percent(reportServiceImpl.calculatePercent(equipRiskNumSum.getYhfb4Num(), yhfbNumSum));
        }

        //第一部分 ----- 三、问题汇总表
        List<wthzPart3Map> wthzPart3MapList = mapperUtils.getMachineinfoMapper().getEquipProblemInfo(checkId, projectId);
        dataMap.setWthzPart3List(wthzPart3MapList);

        //第一部分 ----- 四、安全情况及改进建议
        List<glgjPart4Map> glgjPart4MapList = mapperUtils.getMachineinfoMapper().getProblemSummaryInfo(checkId, projectId);

        //去重
        List<glgjPart4Map> glgjPart4MapListDistinct = glgjPart4MapList.stream().distinct().collect(Collectors.toList());

        //处理结果展示形式，相同设备合并改进建议
        Map<String, String> glgjMap = new HashMap<>();
        for (int i = 0; i < glgjPart4MapListDistinct.size(); i++) {
            glgjPart4Map glgjPart4MapItem = glgjPart4MapListDistinct.get(i);
            if (glgjMap.get(glgjPart4MapItem.getGlgjType()) != null) {
                if (glgjPart4MapItem.getGlgjSuggestion() != null && glgjPart4MapItem.getGlgjSuggestion() != "null") {
                    glgjMap.put(glgjPart4MapItem.getGlgjType(), glgjMap.get(glgjPart4MapItem.getGlgjType()) + "  \r  " + glgjPart4MapItem.getGlgjSuggestion());
                }
            } else {
                glgjMap.put(glgjPart4MapItem.getGlgjType(), "    " + glgjPart4MapItem.getGlgjSuggestion());
            }
        }
        List<glgjPart4Map> newglgjPart4MapList = new LinkedList<>();
        int index = 1;
        for (String key : glgjMap.keySet()) {
            String summary = StringUtils.isBlank(glgjMap.get(key)) ? "    暂无小结" : glgjMap.get(key);
            glgjPart4Map tmp = new glgjPart4Map(index, key, summary);
            newglgjPart4MapList.add(tmp);
            index++;
        }

        dataMap.setGlgjPart4List(newglgjPart4MapList);

        //第二部分 各分项工程检查情况
        List<section2Map> section2MapList = mapperUtils.getMachineinfoMapper().getEquipCheckResultInfo(checkId, projectId);
        //处理序号和图片地址
        for (section2Map section2MapItem : section2MapList) {
            for (int i = 0; i < section2MapItem.getSection2Inner1List().size(); i++) {
                section2Inner1Map section2Inner1MapItem = section2MapItem.getSection2Inner1List().get(i);
                //序号
                section2Inner1MapItem.setSection2Number(i + 1);
                //图片
                List<String> section2ImageMapList = new LinkedList<>();
                JSONArray section2picNameArray = JSONArray.parseArray(section2Inner1MapItem.getSection2PicName());
                if (section2picNameArray == null || section2picNameArray.size() == 0) {
                    //todo 报告本地测试
                    //String s = MDoc.getImageStr("D:\\Work\\LabWork\\YiRui\\文档\\Test\\Pic\\noPic.png");
                    String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");
                    section2ImageMapList.add(s);
                } else {
                    for (int j = 0; j < section2picNameArray.size(); j++) {
                        //todo 报告本地测试
                        //String s = MDoc.getImageStr("D:\\Work\\LabWork\\YiRui\\文档\\Test\\Pic\\noPic.png");
                        String s = MDoc.getImageStr(section2Inner1MapItem.getSection2PicPath() + section2picNameArray.getString(j));
                        section2ImageMapList.add(s);
                    }
                }
                section2Inner1MapItem.setSection2ImageList(section2ImageMapList);
            }
        }
        dataMap.setSection2List(section2MapList);

        //生成报告
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        String fileNameTime = dateTimeFormatter.format(LocalDateTime.now());
        String reportName = projectInfo.getProjectName().replace('#', '号') + "房建设备专项评估报告" + fileNameTime;
        String ftlName = "houseEquipAssessReport";

        BeanMap beanMap = new BeanMap(dataMap);

        return ReportCommonFunc.generateReport(beanMap, reportName, ftlName);

    }


}
